// TurtleWnd.cpp: implementation of the CTurtleWnd class.
//
//////////////////////////////////////////////////////////////////////

#include "TurtleWnd.h"
#include "CanvasDoc.h"
#include <math.h>
#include <assert.h>

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

#define TURTLE_POINTS 3
#define TURTLE_COLOR    RGB(56, 127, 56)
#define PI 3.1415927
#define TURTLE_HIEGHT 16
#define TURTLE_WIDTH  12
const POINT ptTriangle[TURTLE_POINTS] = { {0, -TURTLE_HIEGHT/2}, 
                                          {-TURTLE_WIDTH/2, TURTLE_HIEGHT/2}, 
                                          {TURTLE_WIDTH/2, TURTLE_HIEGHT/2} };


CTurtleWnd::CTurtleWnd()
{
    m_brTurtle = CreateSolidBrush(TURTLE_COLOR);
}

CTurtleWnd::~CTurtleWnd()
{
	if (m_brTurtle) {
		DeleteObject(m_brTurtle);
	}
}

HWND CTurtleWnd::CreateTurtleWnd(HWND hParent, RECT& rect)
{
	return Create(hParent, rect, NULL, WS_VISIBLE|WS_CHILD);
}

LRESULT CTurtleWnd::OnEraseBkgnd(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	assert (m_brTurtle);
	// This has been handled and no default action should been taken.
	HDC dc = (HDC)wParam;
	RECT rc;
	
	GetClientRect(&rc);
	FillRect(dc, &rc, m_brTurtle);
	bHandled = 1;
	return 1;
}

void CTurtleWnd::DrawTurtle(CCanvasDoc* pDoc)
{
	assert (pDoc);

	if (!pDoc->m_bShowTurtle) {
		ShowWindow(SW_HIDE);
		return;
	}

	ShowWindow(SW_SHOW);
	HRGN rgn = CreateTurtleRgn(pDoc);
	SetWindowRgn(m_hWnd, rgn, true);
	return;
}

HRGN CTurtleWnd::CreateTurtleRgn (CCanvasDoc* pDoc)
{
	assert (pDoc);
    int i;
	POINT turtlePoints[TURTLE_POINTS];

    for (i = 0; i < TURTLE_POINTS; i++) {
        double randian = - (pDoc->m_direction * PI) / 180;
        turtlePoints[i].x = (LONG)( ptTriangle[i].x * cos (randian)) - (LONG)(ptTriangle[i].y * sin(randian));
        turtlePoints[i].y = (LONG)( ptTriangle[i].x * sin (randian)) + (LONG)(ptTriangle[i].y * cos(randian));
        turtlePoints[i].x += pDoc->m_ptCurrent.x;
        turtlePoints[i].y += pDoc->m_ptCurrent.y;
    }
    return CreatePolygonRgn (turtlePoints, TURTLE_POINTS, ALTERNATE);
}

